package com.example.demo.leetcode.jianzhi;

import java.util.Arrays;

/**
 * @author xujimou
 * @version 2.0
 * @Description
 * @date 2021/5/20 9:31
 */
public class Btree_重建二叉树 {

  public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }

    public static TreeNode buildTree(int[] preorder, int[] inorder) {

      //1.拿到前序的第一个节点，去中序中查找 找到中间点
      if(preorder.length == 0 || inorder.length == 0){
          return null;
      }
        int rootVal = preorder[0];
        TreeNode root = new TreeNode(rootVal);
        //获取左边数组 右边数组
        for(int i=0;i<inorder.length;i++){
            if(inorder[i] == rootVal){
                int[] pre_left = Arrays.copyOfRange(preorder, 1, i+1); //1,2
                int[] pre_right = Arrays.copyOfRange(preorder, i+1>preorder.length?preorder.length:i+1, preorder.length); //2,3
                int[] in_left = Arrays.copyOfRange(inorder, 0, i+1); //0,2
                int[] in_right = Arrays.copyOfRange(inorder, i+1, inorder.length); //2,2
                root.left=buildTree(pre_left,in_left);
                root.right=buildTree(pre_right,in_right);
            }
        }
        return root;
    }

    public static void main(String[] args) {
      int [] arr = {1,2,3};
      int [] inorder = {2,1,3};
        TreeNode treeNode = buildTree(arr, inorder);
        System.out.println(true);

    }

}
